var express = require('express');
var router = express.Router();
const mongodb= require('../components/mongo');

const multer = require('multer');
const storage = multer.memoryStorage();
const uploader = multer({storage:storage});
const fs = require('fs');
const hostIP = require('../components/host').HOST;


router.get('/',function(req, res, next) {
   res.render('modify_userSample',{title:'ModifySample'});
}).post('/',uploader.single("avatar"),async function(req, res) {
   console.log(req.body);
   console.log(req.file);
var m_uid = req.body.u_id;
   var m_name = req.body.name;
   var m_password = req.body.password;
   var m_email = req.body.email;
   var m_phone = req.body.phone;
   var m_hobby = req.body.hobby;
   var m_content = req.body.content;
   const result = await mongodb.find("User",{u_id:m_uid});
   console.log(result);
   if(result.length == 0){
	   res.json({errno:0,errmsg:"",data:{res:false}});
   }else{
	   const local = "public/";
	   const user_storage_path = "storage/users/";
	   
	   var fileFormat = (req.file.originalname).split(".");
	   var filename = req.file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1];
	   
	   var dirPath = local + user_storage_path + m_uid;
	   var filePath = dirPath + '/' + filename;
	   
	   fs.writeFileSync(filePath,req.file.buffer);
	   var pre_insert = {
		   u_id:m_uid,
		   name:m_name,
		   password:m_password,
		   email:m_email,
		   phone:m_phone,
		   hobby:m_hobby,
		   content:m_content,
		   head_image:hostIP+user_storage_path+ m_uid + '/' + filename,
	   }
	   const insert_result = await mongodb.update("User",result[0],pre_insert);
	   res.json({
		   errno:0,
		   errmsg:"",
		   data:{res:true},
		   });
   }
});




module.exports = router;